

export function createAutoTimer(time: Date, tag="span", parentNode:HTMLElement|null=null): HTMLElement {
    const autotime = document.createElement(tag);
    autotime.className = "autotimer";
    autotime.style.color = "red";
    
    // 格式化绝对时间
    const absoluteTime = time.toLocaleString();
    
    // 更新显示内容的函数
    const updateDisplay = () => {
        const now = new Date();
        const diffMs = now.getTime() - time.getTime();
        const relativeTime = formatRelativeTime(diffMs);
        autotime.textContent = `${absoluteTime} (${relativeTime})`;
    };
    
    // 初始显示
    updateDisplay();
    
    // 每秒更新相对时间
    const interval = setInterval(updateDisplay, 1000);
    
    // 清理定时器的方法（当元素被移除时）
    const observer = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
            mutation.removedNodes.forEach((node) => {
                if (node === autotime || node.contains?.(autotime)) {
                    clearInterval(interval);
                    observer.disconnect();
                    // console.log("Auto timer removed:", autotime);
                }
            });
        });
    });
    
    // 监听DOM变化以清理定时器
    if (parentNode) {
        observer.observe(parentNode, { childList: true, subtree: true });
    }
    
    return autotime;
}

// 辅助函数：格式化相对时间
function formatRelativeTime(diffMs: number): string {
    const seconds = Math.floor(diffMs / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);

    if (days > 0) {
        return `${days}天前`;
    } else if (hours > 0) {
        return `${hours}小时前`;
    } else if (minutes > 0) {
        return `${minutes}分钟前`;
    } else if (seconds > 0) {
        return `${seconds}秒前`;
    } else {
        return "刚刚";
    }
}